import { VuexModule, Module, Action, Mutation, getModule } from 'vuex-module-decorators'
import { getToken, setToken, removeToken } from '@/utils/cookie'
import store from '@/store'

export interface IUserState {
  token: string
  name: string
  avatar: string
  roles: string[]
}
export interface IUser {
  avatar: string
  avatar_url: string
  desc: string | null
  realname: string
  svr_time: 1615280384
  uid: string
  username: string
}

@Module({ dynamic: true, store, name: 'user' })
class User extends VuexModule implements IUserState {
  public token = getToken() || ''
  public name = ''
  public avatar = ''
  public roles: string[] = []
  private USER_INFO_KEY = 'USER_INFO_KEY'
  public userInfo: Partial<IUser> = JSON.parse(localStorage.getItem(this.USER_INFO_KEY) as string) || {}

  @Mutation
  private SET_TOKEN(token: string) {
    this.token = token
  }

  @Mutation
  private SET_AVATAR(avatar: string) {
    this.avatar = avatar
  }

  @Mutation
  private SET_USER_INFO(user: Partial<IUser>) {
    this.userInfo = user
  }

  // 保存登录凭证
  @Action
  setAuth(token: string) {
    this.SET_TOKEN(token)
    setToken(token)
  }

  @Action
  public ResetToken() {
    removeToken()
    this.SET_TOKEN('')
  }

  @Action
  public async LogOut() {
    if (this.token === '') {
      throw Error('LogOut: token is undefined!')
    }
    // await logout()
    removeToken()
    this.removeUserInfo()
    this.SET_TOKEN('')
    this.SET_AVATAR('')
  }

  @Action
  public setUserInfo(user: Partial<IUser>) {
    localStorage.setItem(this.USER_INFO_KEY, JSON.stringify(user))
    this.SET_USER_INFO(user as IUser)
  }

  @Action
  public removeUserInfo() {
    localStorage.removeItem(this.USER_INFO_KEY)
    this.SET_USER_INFO({})
  }
}

export const userModule = getModule(User)
